package com.zlx.mall.basic.util;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.io.InputStream;

/**
 * @author qingke
 **/
@Slf4j
@Component
public class InetAddressSearcher implements ApplicationRunner {

    private static Searcher SEARCHER;
    private static final String UNKNOWN = "未知";

    public void initializeSearcher(String classPath) throws IllegalStateException {
        InputStream is = null;
        try {
            ClassPathResource resource = new ClassPathResource(classPath);
            is = resource.getInputStream();
            SEARCHER = Searcher.newWithBuffer(StreamUtils.copyToByteArray(is));
        } catch (Exception e) {
            log.error("Failed To Create Content Cached Searcher", e);
            throw new IllegalStateException(e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception ignore) {
                    // ignore
                }
            }
        }
    }

    public void closeSearcher() {
        if (SEARCHER != null) {
            try {
                SEARCHER.close();
            } catch (Exception ignore) {
                // ignore
            }
        }
    }

    public @NotNull String getCityInfo(String remoteAddress) {
        try {
            // 国家|区域|省份|城市|ISP, 缺省的地域信息默认是0, Nullable
            String data = SEARCHER.search(remoteAddress);
            if (!StringUtils.hasText(data)) {
                return UNKNOWN;
            }

            String[] array = StringUtils.tokenizeToStringArray(data, "|");
            return StringUtils.replace(array[2] + array[3], "0", "");

        } catch (Exception e) {
            log.error("Failed To Search IP2Region, remoteAddress: {}", remoteAddress, e);
        }
        return UNKNOWN;
    }

    public @NotNull String getInfo(String remoteAddress) {
        try {
            // 国家|区域|省份|城市|ISP, 缺省的地域信息默认是0, Nullable
            String data = SEARCHER.search(remoteAddress);
            if (!StringUtils.hasText(data)) {
                return UNKNOWN;
            }
            return data;
        } catch (Exception e) {
            log.error("Failed To Search IP2Region, remoteAddress: {}", remoteAddress, e);
        }
        return UNKNOWN;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            initializeSearcher("ip2region/ip2region.xdb");
        } catch (Exception e) {
            log.error("Failed To Initialize Remote Address Searcher", e);
        }
    }
}
